package gbench.tartarus.hipponoe.stomp;

import gbench.common.matlib.MatlibCanvas;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 *
 *
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        final var patterns = allowOriginPattern.split(",");
        MatlibCanvas.println(patterns);
        // 为/stomp 路径启用SockJS功能
        registry.addEndpoint("/stomp")
            .setAllowedOriginPatterns(patterns)
            .withSockJS();
    }

    @Override
    public void configureMessageBroker(final MessageBrokerRegistry registry) {
        // 使用内置的消息代理进行订阅和广播，并将destination header 以/topic,/queue 或 users 开头的消息路由到代理。
        registry.enableSimpleBroker("/topic");

        // 以/app开头的destination header的STOMP消息被路由到@Controller类中的@MessageMapping方法。
        registry.setApplicationDestinationPrefixes("/app");

        // 给指定用户发送一对一的消息前缀是/users/。
        registry.setUserDestinationPrefix("/users/");
    }

    @Value("${hipponoe.cfg.allow_origin_pattern}")
    private String allowOriginPattern;
}